declare global {
  interface Window {
    io: () => {
      emit: (str: string, val: any) => void;
      on: (str: string, cb: (val: any) => void) => void;
      $emit: (val: any) => void;
      $on: (cb: (data: any) => void) => void;
    };
  }
}

export const scoket = window.io();
scoket.$on = (cb) => {
  scoket.on("chat message", cb);
};
scoket.$emit = (data) => {
  scoket.emit("chat message", data);
};
//#region 响应
interface On {
  role: "p1" | "p2" | "*";
  path: string;
  cb: Function;
}

type Cb = (res: { role: string; path: string; value: any }) => void;

const onQueue: On[] = [];

scoket.on("chat message", (res) => {
  onQueue.forEach((on) => {
    if (on.role === res.role && (on.path === res.path || on.path === "*")) {
      on.cb({ path: on.role, role: on.path, value: res.value });
    }
  });
});

export const on = {
  p1(path: string, cb: Cb) {
    onQueue.push({ role: "p1", path, cb });
  },
  p2(path: string, cb: Cb) {
    onQueue.push({ role: "p2", path, cb });
  },
  all(path: string, cb: Cb) {
    onQueue.push({ role: "*", path, cb });
  },
};
//#endregion

export const emit = {
  p1(path: string, value: any) {
    scoket.emit("chat message", { role: "p1", path, value });
  },
  p2(path: string, value: any) {
    scoket.emit("chat message", { role: "p2", path, value });
  },
};
